<?php

namespace addons\shopro\controller;

use app\admin\model\ReceiveBuilding;
use app\admin\model\ReceiveGift;
use app\admin\model\ReceiveRoom;
use app\api\model\ReceiveGiftModel;
use app\common\library\Sms;
use app\common\library\Sms as Smslib;
use app\common\model\User;
use think\Db;
use think\Hook;
use think\Log;
use think\Model;
use think\Request;
use think\Validate;
use EasyWeChat\Factory;
use app\admin\model\shopro\Config;

/**
 * 领取礼品接口
 */
class Gift extends Base
{
    protected $noNeedLogin = ['getBuildingNo', 'getRoomNo','send','roomtype','building','floor','room'];
    protected $noNeedRight = ['*'];

    /**
     * 发送验证码
     *
     * @param string $mobile 手机号
     * @param string $event 事件名称
     */
    public function send()
    {
        $mobile = $this->request->param("mobile");
        $event = $this->request->param("event");
        $event = $event ? $event : 'register';

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        $last = Smslib::get($mobile, $event);
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('发送频繁'));
        }
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
            $this->error(__('发送频繁'));
        }
        if ($event) {
            $userinfo = User::getByMobile($mobile);
            if ($event == 'register' && $userinfo) {
                //已被注册
                $this->error(__('已被注册'));
            } elseif (in_array($event, ['changemobile']) && $userinfo) {
                //被占用
                $this->error(__('已被占用'));
            } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
                //未注册
                $this->error(__('未注册'));
            }
        }
        if (!Hook::get('sms_send')) {
            $this->error(__('请在后台插件管理安装短信验证插件'));
        }
        $ret = Smslib::send($mobile, null, $event);
        if ($ret) {
            $this->success(__('发送成功'));
        } else {
            $this->error(__('发送失败，请检查短信配置是否正确'));
        }
    }

    public function getwxphone()
    {
        $input = input();
        $configmodel = new Config();
        $config = $configmodel->where(['name'=>'wxMiniProgram'])->find();
        $data = $config['value'];
        $data  =json_decode($data);
        $config = [
            'app_id' => "$data->app_id" ,
            'secret' => "$data->secret",
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];

        $app = Factory::miniProgram($config);
        $session = $app->auth->session($input['code']);
        $decryptedData = $app->encryptor->decryptData($session['session_key'] , $input['iv'], $input['encryptedData']);
        $this->success('请求成功',$decryptedData['phoneNumber']);
    }


    /**
     * 首页
     *
     */
    public function receive()
    {
        $name = $this->request->param('name');
        $mobile = $this->request->param('mobile');
        $cat = $this->request->param('cat');
        $receive_type_id = $this->request->param('receive_type_id');
        $building_no = $this->request->param('building_no');
        $floor_no = $this->request->param('floor_no');
        $room_no = $this->request->param('room_no');
        if(empty(input('name'))){
            $this->error("请输入姓名");
        }
        if (!Validate::regex($mobile, "^1[3-9]\d{9}$")) {
            $this->error(__('手机号格式不正确'));
        }
        if(empty(input('remark')) && ($cat == '员工' || $cat == "访客")){
            if($cat == "员工"){
                $this->error("请输入公司名字");
            }else{
                $this->error("请输入访客事由");
            }
        }
        if ((!$name || !$mobile || !$cat || !$receive_type_id || !$building_no || !$room_no) && $cat == '业主') {
            $this->error(__('信息请填写完全'));
        }


        $user_id = $this->auth->id;
        $exists = ReceiveGift::where('user_id', $user_id)->find();
        $input = input();
        $input['user_id'] = $user_id;
        if($exists){
            $model = new ReceiveGift();
            if($cat != '业主'){
                $input['receive_type_id'] ='';
                $input['building_no'] ='';
                $input['floor_no'] ='';
                $input['room_no'] ='';
            }
            $ret = $model->allowField(true)->save($input,['id' => $exists['id']]);
        }else{
            $model = new ReceiveGift($input);
            $ret = $model->allowField(true)->save();
        }
        if ($ret) {
            User::update(['group_id'=>2],['id'=>$user_id]);
            $this->success('请求成功');
        } else {
            //$this->error('请求失败');
            $this->success('请求成功');
        }
    }

    public function getreceivelist(){
        $user_id = $this->auth->id;
        $input = input();
        $id = isset($input['id']) ? $input['id'] : '';
        $where = [];
        if(!empty($id)){
            $where = ['id'=>$id];
        }
        $data = ReceiveGift::where('user_id', $user_id)
            ->where($where)
            ->order('createtime','desc')
            ->paginate($input['limit']);
        $this->success('请求成功',$data);
    }

    public function checkstatus(){
        $input = input();
        $user_id = $this->auth->id;
        if(isset($input['code'])){
            $data = ReceiveGift::where(['user_id'=>$user_id])->delete();
        }
        $data = ReceiveGift::where(['user_id'=>$user_id])->order('createtime','desc')->find();
        if(empty($data)){
            $this->success('请求成功',$data,2);
        }
        $this->success('请求成功',$data);
    }
    /*
     * 获取楼号
     */
    public function getBuildingNo()
    {
        $data = ReceiveBuilding::column('no');
        $this->success('请求成功', $data);
    }

    /*
     * 获取房间号
     */
    public function getRoomNo()
    {
        $data = ReceiveRoom::column('room_no');;
        $this->success('请求成功', $data);
    }

    public function roomtype()
    {
        $list = Db::table('fa_receive_type')->field('id as type_id,type_name')->whereNull('deletetime')->select();
        $this->success("成功", $list);
    }

    public function building()
    {
        $list = Db::table('fa_receive_building')
            ->where('receive_type_id', input('type_id'))
            ->field('id as building_id,building_id as no')
            ->select();
        $this->success("成功", $list);
    }

    public function floor()
    {
        $list = Db::table('fa_receive_floor')
            ->where('receive_type_id', input('type_id'))
            ->where('building_id', input('building_id'))
            ->field('id as floor_id,floor_no')
            ->select();
        $this->success("成功", $list);
    }

    public function room()
    {
        $list = Db::table('fa_receive_room')
            ->where('receive_type_id', input('type_id'))
            ->where('building_id', input('building_id'))
            ->where('floor_id', input('floor_id'))
            ->field('id as room_id,room_no')
            ->select();
        $this->success("成功", $list);
    }

}
